<template>
  <div class="makeorder-container">
    <el-card class="makeorder-card">
      <template #header>
        <div class="card-header">
          <span>管理员下订单</span>
        </div>
      </template>

      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderFormRules"
        label-width="100px"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户" prop="userId">
              <el-select
                v-model="orderForm.userId"
                placeholder="请选择用户"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.name + ' (' + user.phone + ')'"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商户" prop="merchantId">
              <el-select
                v-model="orderForm.merchantId"
                placeholder="请选择商户"
                style="width: 100%"
                @change="onMerchantChange"
              >
                <el-option
                  v-for="merchant in merchantList"
                  :key="merchant.id"
                  :label="merchant.name"
                  :value="merchant.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiverName">
              <el-input
                v-model="orderForm.receiverName"
                placeholder="请输入收货人姓名"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="receiverPhone">
              <el-input
                v-model="orderForm.receiverPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="orderForm.address"
            placeholder="请输入详细收货地址"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="商品信息" prop="products">
          <el-table
            :data="orderForm.products"
            style="width: 100%"
          >
            <el-table-column prop="name" label="商品名称" width="150" />
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  size="small"
                  @change="calculateTotal"
                />
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计" width="100">
              <template #default="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeProduct(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="add-product-section">
            <el-select
              v-model="selectedProduct"
              placeholder="请选择商品"
              style="width: 300px; margin-right: 10px"
              clearable
            >
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.name + ' (¥' + product.price + ')'"
                :value="product.id"
              />
            </el-select>
            <el-button
              type="primary"
              icon="Plus"
              @click="addProduct"
            >
              添加商品
            </el-button>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送费" prop="deliveryFee">
              <el-input-number
                v-model="orderForm.deliveryFee"
                :min="0"
                :step="0.1"
                controls-position="right"
                style="width: 100%"
                @change="calculateTotal"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="订单总额" prop="totalAmount">
              <el-input
                v-model="orderForm.totalAmount"
                readonly
                prefix-icon="el-icon-money"
              >
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="orderForm.remark"
            placeholder="请输入订单备注信息"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表单引用
const orderFormRef = ref()

// 选中的商品
const selectedProduct = ref('')

// 用户列表
const userList = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138001'
  },
  {
    id: 2,
    name: '李四',
    phone: '13800138002'
  },
  {
    id: 3,
    name: '王五',
    phone: '13800138003'
  }
])

// 商户列表
const merchantList = ref([
  {
    id: 1,
    name: '肯德基'
  },
  {
    id: 2,
    name: '麦当劳'
  },
  {
    id: 3,
    name: '必胜客'
  }
])

// 商品列表
const productList = ref([
  {
    id: 1,
    name: '香辣鸡腿堡',
    price: 25.00,
    merchantId: 1
  },
  {
    id: 2,
    name: '薯条',
    price: 12.00,
    merchantId: 1
  },
  {
    id: 3,
    name: '可乐',
    price: 8.00,
    merchantId: 1
  },
  {
    id: 4,
    name: '巨无霸',
    price: 28.00,
    merchantId: 2
  },
  {
    id: 5,
    name: '麦辣鸡翅',
    price: 15.00,
    merchantId: 2
  },
  {
    id: 6,
    name: '披萨',
    price: 68.00,
    merchantId: 3
  }
])

// 订单表单
const orderForm = reactive({
  userId: '',
  merchantId: '',
  receiverName: '',
  receiverPhone: '',
  address: '',
  deliveryFee: 3.00,
  totalAmount: 0,
  remark: '',
  products: []
})

// 表单验证规则
const orderFormRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  merchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  products: [
    { required: true, type: 'array', min: 1, message: '请至少添加一个商品', trigger: 'change' }
  ]
}

// 当商户改变时，清空商品列表和已选商品
// const onMerchantChange = (merchantId) => {
//   orderForm.products = []
//   selectedProduct.value = ''
//   calculateTotal()
// }

// 添加商品
const addProduct = () => {
  if (!selectedProduct.value) {
    ElMessage.warning('请选择商品')
    return
  }

  // 检查商品是否已添加
  const existingProduct = orderForm.products.find(p => p.id === selectedProduct.value)
  if (existingProduct) {
    ElMessage.warning('该商品已添加，请直接修改数量')
    return
  }

  // 查找选中的商品
  const product = productList.value.find(p => p.id === selectedProduct.value)
  if (product) {
    orderForm.products.push({
      id: product.id,
      name: product.name,
      price: product.price,
      quantity: 1
    })
    selectedProduct.value = ''
    calculateTotal()
  }
}

// 删除商品
const removeProduct = (index) => {
  orderForm.products.splice(index, 1)
  calculateTotal()
}

// 计算总金额
const calculateTotal = () => {
  let productTotal = 0
  orderForm.products.forEach(product => {
    productTotal += product.price * product.quantity
  })

  orderForm.totalAmount = (productTotal + orderForm.deliveryFee).toFixed(2)
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orderFormRef.value.resetFields()
    orderForm.products = []
    orderForm.deliveryFee = 3.00
    orderForm.totalAmount = 0
    selectedProduct.value = ''
    ElMessage.success('表单已重置')
  }).catch(() => {
    // 取消操作
  })
}

// 提交订单
const submitOrder = () => {
  orderFormRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('确定要提交订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用接口提交订单
        console.log('提交订单:', orderForm)
        ElMessage.success('订单提交成功')
        resetForm()
      }).catch(() => {
        // 取消操作
      })
    } else {
      ElMessage.error('请填写完整信息')
      return false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  ElMessage.success('下订单页面加载完成')
})
</script>

<style scoped>
.makeorder-container {
  padding: 20px;
  background-color: #f0f2f5;
  height: 100%;
  box-sizing: border-box;
}

.makeorder-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-product-section {
  margin-top: 15px;
  display: flex;
  align-items: center;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}
</style>
